let  fs = require('fs');
const path = require('path')
let file = path.resolve(__dirname, './img.txt')
let  join = require('path').join;
const moment = require('moment');
/**

 * 

 * @param startPath  起始目录文件夹路径

 * @returns {Array}

 */

function findSync(startPath) {

    let result=[];

    function finder(path) {

        let files=fs.readdirSync(path);

        files.forEach((val,index) => {

            let fPath=join(path,val);
            let stats=fs.statSync(fPath);
            if(stats.isDirectory()) finder(fPath);

            if(stats.isFile()) result.push({'path':fPath,'mtime':moment(stats.mtime).format("'YYYY-MM-DD HH:mm:ss'")});
            

        });


    }

    finder(startPath);
   let objarr =  selectArr(result);
   let newarr = []
   objarr.forEach((val)=>{
    newarr.push(val.path)
   })
    return newarr;

}

function selectArr(arr){
    var min,temp;
    for(var i =0;i<arr.length-1;i++){
        min = i;
        for(var j=i+1;j<arr.length;j++){
            if(arr[j].mtime<arr[min].mtime){
                min =j;
            }
        }
        temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
    }

    return arr;
}
let fileNames=findSync('./img');
fs.writeFile(file, JSON.stringify(fileNames, null, 4), { encoding: 'utf8' }, err => {})